#include <iostream>
#include <vector>

using namespace std;
class Solution
{
public:
    int maxSubArray(vector<int> &nums)
    {
        int numsSize = nums.size();
        if (numsSize == 1)
        {
            return nums[0];
        }
        int sum = nums[0], maxsum = nums[0];

        for (int i = 1; i < numsSize; i++)
        {
            if (sum + nums[i] <= nums[i])
            {
                sum = nums[i];
            }
            else
            {
                sum = sum + nums[i];
            }

            if (sum > maxsum)
            {
                maxsum = sum;
            }
        }
        return maxsum;
    }

    int maxSubArray_2(vector<int> &nums)
    {
        int pre = 0, maxAns = nums[0];
        for (const auto &x : nums)
        {
            pre = max(pre + x, x);
            maxAns = max(maxAns, pre);
        }
        return maxAns;
    }
};
int main()
{
    Solution s;
    vector<int> nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
    cout << s.maxSubArray(nums) << endl;
    system("pause");
    return 0;
}
